<?php
	ob_end_clean();
	ob_start();
	
	$isbat = false; 
	if (isset($_POST["year4"]) ){
		$isbat = false;
	}else {
		$isbat = true; 
	}
	if ($isbat) {
		$inc_path = "/home/sub52846/www/aoki";
	} else 
	{
		$inc_path = "..";
		require_once( $inc_path.'/system/smarty.inc' );
		require_once( $inc_path.'/system/login.inc.php' );
	}
	
	require_once( $inc_path.'/system/tdao/Class_B_HISTORY.php' );
	require_once( $inc_path.'/system/mdao/Class_M_SHOP_RHIZOME.php' );
	require_once( $inc_path.'/system/mdao/Class_M_INS_SHOP.php' );	
	require_once( $inc_path.'/system/mdao/Class_M_INS_SHOP_RHIZOME.php' );
	require_once( $inc_path.'/system/mdao/Class_M_OTHER.php' );
	require_once( $inc_path.'/system/Class_FILE_CSV.php' );
	require_once( $inc_path.'/system/Class_ERROR.php' );
	require_once( $inc_path.'/system/aoki_m.php' );
	require_once( $inc_path.'/system/aoki_rhizome.php' );
	require_once( $inc_path.'/system/Class_PWD.php' );
	
	
	$hdao = new Class_B_HISTORY();
	

	
	$importsort = 1;
	$newline = "<br>";
	if ($isbat) {
		$newline = "\n";
		$importsort =  $argv[1];
		
	}else {
		if ( isset($_POST['sort']) ) {
			$importsort = $_POST['sort'];
		}
	}
	

	if ( isset($_POST['matrix_cd']) && (!empty($_POST['matrix_cd'])) ) {
		$matrix_cd =  $_POST['matrix_cd'];
		$isbat = false;  
	} else {
		$matrix_cd =  Class_M_OTHER::get_laster_matrix_cd();
	}
	
	$week_cd = substr($matrix_cd,4,2);
	
	
	if ( isset( $aoki_rhizome_files[$importsort] ) ) {
		$file_csv  =  $aoki_rhizome_files[$importsort] ;
	} else {
		echo "パラメタはエラー";
		exit;
	}
	$can_export = false ;
	if ($importsort == 4 || $importsort == 5 ) {
		$can_export = true ;
		$file_csv = $file_csv. '';
	}
	if (!$isbat) {
		if  ($can_export) {

		} else {
			echo '<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
				<meta http-equiv="Content-Script-Type" content="text/javascript" />
				<meta http-equiv="Content-Style-Type" content="text/css" />
		
			</head>
		<body> ' ;
		}
	}
	$hvalues = array();
	
	$hvalues["matrix_cd"]  = $matrix_cd;
	$hvalues["start_time"] = date("Y-m-d H:i:s",time());
	$hvalues["sort"]       = $importsort;
	if ($isbat){
		$hvalues["u_user"]  = 0;
	} else {
		$hvalues["u_user"]  = $_SESSION['ADMIN_LOGIN']['STAFF_SEQ'];
	}
	
	$file_all_shop =  "";
	$docsv_import = FALSE;
	
	
	$file_error = false;
	if ($can_export) {
		
	} else {
		$csvf = $aoki_batch_path.$file_csv.".csv";
		if   ( !file_exists($csvf))   {
			 $file_error = true;
		} 
	}
	
	$update_ok = false; 


	if ((!$can_export) && (!$file_error) ) {
		// ロケール情報の変更
		$locale = setlocale(LC_ALL, 0);
		setlocale(LC_ALL,'ja_JP.UTF-8');
		$rowall = Class_FILE_CSV::fget_rows($csvf);
		
		if  ( !empty($rowall)  ) {
		//*****販売店処理開始******************************************************************
		if ($importsort == 1) {
			$col_heads = array(
			''                   , //媒体
			'ins_shop_cd'        , //販売店コード
			''    		         , //販売店エリア
			'now_quantity'       , //本年経準高
			'last_quantity'      , //昨年経準高
			'diff_quantity'      , //差異経準高
			'rate_quantity'      , //前比経準高
			'now_sales'          , //本年売上客数
			'last_sales'         , //昨年売上客数
			'diff_sales'         , //差異売上客数
			'rate_sales'         , //前比売上客数
			'now_price'          , //本年客単価
			'last_price'         , //昨年客単価
			'diff_price'         , //差異客単価
			'rate_price'         , //前比客単価
			''                   , //集計開始日
			''                     //集計終了日
			);
			$csvheads  = array();
			$col_index = array();
			foreach ($col_heads as $k => $v) {
				if (!empty($v)) {
					$csvheads[$k]  = $v;
					$col_index[$v] = $k;
				}
			} 
			
			$key1 = $col_index['ins_shop_cd'];//キーです、必ず仕様します
			$err = new Class_ERROR("","");
			$dao = new Class_M_INS_SHOP_RHIZOME;
			
			$ngline  = 0;
			$error_times = 0;
			$error_stop = IMPORT_STOP_MAX_ERROR_TIMES;
			$errtext = array();
			$isng = FALSE;
			
			$chk     = $dao->get_checks();
			$chklens = $dao->get_maxlens();
			
			$linecount = count($rowall);
			$percentold = 100;
 			foreach ($rowall as $line => $row) {
				$isng = FALSE;
				if ($isbat) {
					
				}else {
					$percent = intval($line/$linecount * 100)."%";
					if  ( $percent != $percentold ) {
						Class_FILE_CSV::write_msg_checking_per( $percent ) ;
					}
					$percentold = $percent;
				}
				//CSV内部重複不可チェック
				foreach ($rowall as $kk=>$vv) {
					if  ($line != $kk) {
						if ($row[$key1] == $vv[$key1]){
							$col = $key1 + 1;
							$isng = TRUE;
							$ngMsg_tmp[$line][] = "{$line}行と{$kk}行の{$col}列目の値重複不可。";
							$error_times++;
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				} 
				//普通チェック
				foreach ( $csvheads as $k=>$v ) {
					$msg =  $err->check( $rowall[$line][$k], $chk[$v ] ); 
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $k+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
				//桁数チェック
				foreach ( $chklens as $k => $v ) {
					if (isset($col_index[$k])){
						$msg = $err->check_size($rowall[$line][$col_index[$k]], $v);
						if (!empty($msg)) {
							$isng = TRUE;
							$col  = $col_index[$k]+1;
							$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
							$error_times++;					
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				}
				
				//for (i)lnews1
				if ( $isng ) {
					++$ngline;
					$errtext[$ngline] = $row;
					if ($error_times > $error_stop) {
						break;
					}
				}
			}
			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);
				if ($error_times > $error_stop) {
					$errHtml = "エラー数は１００件を超えました！！" .$vv.$errHtml ;
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );
					}
				} else {
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml );
					}
				}
				$hvalues["end_time"] = date("Y-m-d H:i:s",time());
				$hvalues["result_flg"] = 1;
				$hvalues["result_msg"] = $errHtml;
				$hdao->write_bhistory( $hvalues );
				
			} else {
				//DBへ更新
				try {
					
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					
					$where = sprintf(" matrix_cd = '%s'", $matrix_cd );
					$dao->del($where) ;
					foreach ( $rowall as $k=>$v ) {
						$i++;
						if ($isbat) {
							
						}else {
							$percent = intval($i/$line * 100)."%";
							if  ( $percent != $percentold ) {
	
								Class_FILE_CSV::write_msg_doing( $percent );
							}
							$percentold = $percent;
						}
					
						$values  = array();
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						$values["matrix_cd"] = $matrix_cd ;
						$keyvalues =  $values[$col_heads[$key1]];
						
						
					//	if ( $dao->exits( $where ) ) {
					//		if (!($dao->editbycol($keyvalues ,$values ,$col_heads[$key1] ))) {
					//			throw exception("mrhizome_import","db更新", AOKI_OTHER, "File not opend");
					//		}
					//	} else {
						if ( !( $dao->add($values ) ) ) {
							throw new Exception("mrhizome_import error");
						}
					//	}
					}
					if ($isbat) {
						//$hdao->write_msg_succed($line );
					}else {
						Class_FILE_CSV::write_msg_succed($line, "mrhizome");
					}
					$dao->commit_trans();
					
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 0;
					$hvalues["result_msg"] = "{$line}件データがインポートされました";
					
					$hdao->write_bhistory( $hvalues );
					$update_ok = true;
				} catch (Exception $e) {
					$dao->rollback_trans();

					
					if ($isbat) {
						$hdao->push_msg_error(  "DB Exceptionがありました。{$newline}" );
						
					}else {
						Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。{$newline}" );
					}
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 2;
					$hvalues["result_msg"] = "DB Exceptionがありました。";
					$hdao->write_bhistory( $hvalues );
				}
			} 
			} 
			
		//*****販売店処理終了******************************************************************
		//*****店舗処理開始******************************************************************
		if ($importsort == 2) {
			$col_heads = array(
			'shop_cd'            , //店舗コード
			''    		         , //店舗
			'now_quantity'       , //本年経準高
			'last_quantity'      , //昨年経準高
			'diff_quantity'      , //差異経準高
			'rate_quantity'      , //前比経準高
			'now_sales'          , //本年売上客数
			'last_sales'         , //昨年売上客数
			'diff_sales'         , //差異売上客数
			'rate_sales'         , //前比売上客数
			'now_price'          , //本年客単価
			'last_price'         , //昨年客単価
			'diff_price'         , //差異客単価
			'rate_price'         , //前比客単価
			''                   , //集計開始日
			''                     //集計終了日
			);
			$csvheads  = array();
			$col_index = array();
			foreach ($col_heads as $k => $v) {
				if (!empty($v)) {
					$csvheads[$k]  = $v;
					$col_index[$v] = $k;
				}
			} 
			
			$key1 = $col_index['shop_cd'];//キーです、必ず仕様します
			$err = new Class_ERROR("","");
			$dao = new Class_M_SHOP_RHIZOME;
			
			$ngline  = 0;
			$error_times = 0;
			$error_stop = IMPORT_STOP_MAX_ERROR_TIMES;
			$errtext = array();
			$isng = FALSE;
			
			$chk     = $dao->get_checks();
			$chklens = $dao->get_maxlens();
			
			$linecount = count($rowall);
			$percentold = 100;
 			foreach ($rowall as $line => $row) {
				$isng = FALSE;
				if ($isbat) {
					
				}else {
					$percent = intval($line/$linecount * 100)."%";
					if  ( $percent != $percentold ) {
						Class_FILE_CSV::write_msg_checking_per( $percent ) ;
					}
					$percentold = $percent;
				}
				//CSV内部重複不可チェック
				foreach ($rowall as $kk=>$vv) {
					if  ($line != $kk) {
						if ($row[$key1] == $vv[$key1]){
							$col = $key1 + 1;
							$isng = TRUE;
							$ngMsg_tmp[$line][] = "{$line}行と{$kk}行の{$col}列目の値重複不可。";
							$error_times++;
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				} 
				//普通チェック
				foreach ( $csvheads as $k=>$v ) {
					$msg =  $err->check( $rowall[$line][$k], $chk[$v ] ); 
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $k+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
				//桁数チェック
				foreach ( $chklens as $k => $v ) {
					if (isset($col_index[$k])){
						$msg = $err->check_size($rowall[$line][$col_index[$k]], $v);
						if (!empty($msg)) {
							$isng = TRUE;
							$col  = $col_index[$k]+1;
							$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
							$error_times++;					
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				}
				if (isset($col_index[$k])){
					$msg = $err->check_size_equal($row[$key1], 3);
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $key1+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
				
				//for (i)lnews1
				if ( $isng ) {
					++$ngline;
					$errtext[$ngline] = $row;
					if ($error_times > $error_stop) {
						break;
					}
				}
			}
			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);
				if ($error_times > $error_stop) {
					$errHtml = "エラー数は１００件を超えました！！" .$vv.$errHtml ;
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );
					}
				} else {
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml );
					}
				}
				$hvalues["end_time"] = date("Y-m-d H:i:s",time());
				$hvalues["result_flg"] = 1;
				$hvalues["result_msg"] = $errHtml;
				$hdao->write_bhistory( $hvalues );
			} else {
				//DBへ更新
				try {
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					
					$where = sprintf(" matrix_cd = '%s'", $matrix_cd );
					$dao->del($where) ;
					foreach ( $rowall as $k=>$v ) {
						$i++;
						if ($isbat) {
							
						}else {
							$percent = intval($i/$line * 100)."%";
							if  ( $percent != $percentold ) {
	
								Class_FILE_CSV::write_msg_doing( $percent );
							}
							$percentold = $percent;
						}
					
						$values  = array();
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						$values["matrix_cd"] = $matrix_cd ;
						$keyvalues =  $values[$col_heads[$key1]];
						
						
					//	if ( $dao->exits( $where ) ) {
					//		if (!($dao->editbycol($keyvalues ,$values ,$col_heads[$key1] ))) {
					//			throw exception("mrhizome_import","db更新", AOKI_OTHER, "File not opend");
					//		}
					//	} else {
						if ( !( $dao->add($values ) ) ) {
							throw new Exception("mrhizome_import error");
						}
					//	}
					}
					
					if ($isbat) {
						//$hdao->write_msg_succed($line );
					}else {
						Class_FILE_CSV::write_msg_succed($line, "mrhizome");
					}
				
					$dao->commit_trans();
				
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 0;
					$hvalues["result_msg"] = "{$line}件データがインポートされました";
					
					$hdao->write_bhistory( $hvalues );
					
					$update_ok = true;
					//-----------------------------------------------------------------------------

				} catch (Exception $e) {
					$dao->rollback_trans();
					if ($isbat) {
						$hdao->push_msg_error(  "DB Exceptionがありました。{$newline}" );
						
					}else {
						Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。{$newline}" );
					}
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 2;
					$hvalues["result_msg"] = "DB Exceptionがありました。";
					$hdao->write_bhistory( $hvalues );
				}
			} 
			} 
			
			//*****店舗処理終了******************************************************************
			//*****一括処理開始******************************************************************
		if ($importsort == 3) {
			$col_heads = array(
			'ins_shop_cd'     , //販売店コード
			''    		      , //販売店エリア
			'shop_away'       , //店舗からの距離
			'aoki_compete'    , //AOKI/競合
			'home_percent'    , //世帯普及率
			'all_amount'      , //総需要額（億円）
			'sale_share'      , //売上高シェア
			);			
			$csvheads  = array();
			$col_index = array();
			foreach ($col_heads as $k => $v) {
				if (!empty($v)) {
					$csvheads[$k]  = $v;
					$col_index[$v] = $k;
				}
			} 
			
			$key1 = $col_index['ins_shop_cd'];//キーです、必ず仕様します
			$err = new Class_ERROR("","");
			$dao = new Class_M_INS_SHOP;
			
			$ngline  = 0;
			$error_times = 0;
			$error_stop = IMPORT_STOP_MAX_ERROR_TIMES;
			$errtext = array();
			$isng = FALSE;
			
			$chk     = $dao->get_checks();
			$chklens = $dao->get_maxlens();
			
			$linecount = count($rowall);
			$percentold = 100;
 			foreach ($rowall as $line => $row) {
				$isng = FALSE;
				if ($isbat) {
					
				}else {
					$percent = intval($line/$linecount * 100)."%";
					if  ( $percent != $percentold ) {
						Class_FILE_CSV::write_msg_checking_per( $percent ) ;
					}
					$percentold = $percent;
				}
				//CSV内部重複不可チェック
				foreach ($rowall as $kk=>$vv) {
					if  ($line != $kk) {
						if ($row[$key1] == $vv[$key1]){
							$col = $key1 + 1;
							$isng = TRUE;
							$ngMsg_tmp[$line][] = "{$line}行と{$kk}行の{$col}列目の値重複不可。";
							$error_times++;
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				} 
				//普通チェック
				foreach ( $csvheads as $k=>$v ) {
					$msg =  $err->check( $rowall[$line][$k], $chk[$v ] ); 
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $k+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
			
				//桁数チェック
				foreach ( $chklens as $k => $v ) {
					if (isset($col_index[$k])){
						$msg = $err->check_size($rowall[$line][$col_index[$k]], $v);
						if (!empty($msg)) {
							$isng = TRUE;
							$col  = $col_index[$k]+1;
							$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
							$error_times++;					
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				}
				$where = sprintf(" ins_shop_cd = '%s'", $dao->quote( $row[0] ) );
				if ( !$dao->exits( $where ) ) {
					$col = $key1 + 1;
					$isng = TRUE;
					$ngMsg_tmp[$line][] = "{$line}行{$col}列目の販売店コードは存在しません。";
					$error_times++;
					if ($error_times > $error_stop) {
						break;
					}
				}
				
				//for (i)lnews1
				if ( $isng ) {
					++$ngline;
					$errtext[$ngline] = $row;
					if ($error_times > $error_stop) {
						break;
					}
				}
			}
			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);
				if ($error_times > $error_stop) {
					$errHtml = "エラー数は１００件を超えました！！" .$vv.$errHtml ;
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );
					}
				} else {
					if ($isbat) {
						
					}else {
						Class_FILE_CSV::write_msg_error( $errHtml );
					}
				}
				$hvalues["end_time"] = date("Y-m-d H:i:s",time());
				$hvalues["result_flg"] = 1;
				$hvalues["result_msg"] = $errHtml;
				$hdao->write_bhistory( $hvalues );
				
			} else {
				//DBへ更新
				try {
					
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					
					
					$dao->del($where) ;
					foreach ( $rowall as $k=>$v ) {
						$i++;
						if ($isbat) {
							
						}else {
							$percent = intval($i/$line * 100)."%";
							if  ( $percent != $percentold ) {
	
								Class_FILE_CSV::write_msg_doing( $percent );
							}
							$percentold = $percent;
						}
					
						$values  = array();
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						
						$keyvalues =  $values[$col_heads[$key1]];
						
					
						if (!($dao->editbycol($keyvalues ,$values ,$col_heads[$key1] ))) {
							throw exception("mrhizome_import","db更新", AOKI_OTHER, "File not opend");
						}
					}
					if ($isbat) {
						//$hdao->write_msg_succed($line );
					}else {
						Class_FILE_CSV::write_msg_succed($line, "mrhizome");
					}
					$dao->commit_trans();
					
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 0;
					$hvalues["result_msg"] = "{$line}件データがインポートされました";
					
					$hdao->write_bhistory( $hvalues );
					$update_ok = true;
				} catch (Exception $e) {
					$dao->rollback_trans();

					
					if ($isbat) {
						$hdao->push_msg_error(  "DB Exceptionがありました。{$newline}" );
						
					}else {
						Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。{$newline}" );
					}
					$hvalues["end_time"] = date("Y-m-d H:i:s",time());
					$hvalues["result_flg"] = 2;
					$hvalues["result_msg"] = "DB Exceptionがありました。";
					$hdao->write_bhistory( $hvalues );
				}
			} 
			} 
			
		//*****一括処理終了******************************************************************
		}else {
			$errHtml = "CSVファイルエラー";
			if ($isbat) {
				
			}else {
				Class_FILE_CSV::write_msg_error( $errHtml );
			}
			$hvalues["end_time"] = date("Y-m-d H:i:s",time());
			$hvalues["result_flg"] = 1;
			$hvalues["result_msg"] = $errHtml;
			$hdao->write_bhistory( $hvalues );
		}
		
		// ロケール情報の復元
		setlocale(LC_ALL, $locale);
	}
	
	if ($file_error) {
		$errHtml = "CSVファイルは存在しません";
		if ($isbat) {
			
		}else {
			Class_FILE_CSV::write_msg_error( $errHtml );
		}
		$hvalues["end_time"] = date("Y-m-d H:i:s",time());
		$hvalues["result_flg"] = 1;
		$hvalues["result_msg"] = $errHtml;
		$hdao->write_bhistory( $hvalues );
	}
	//---------------------------backup file
	if ( $update_ok && (!$can_export) ) {
		$zip = new ZipArchive();
		$tmpbackupfile = $file_csv.date("YmdHis").'.zip';
		$ret = $zip->open($aoki_batch_path_backup.$tmpbackupfile, ZIPARCHIVE::CREATE);
		if (TRUE !== $ret) {
		    echo("Can't create zip: ".$ret);
		    //exit(1);
		}
		//$csvf = $aoki_batch_path.$file_csv;
		//  ディレクトリの作成
		//	$zip->addEmptyDir('bar');
		//  テキストファイルを追加
		$zip->addFile($csvf,$file_csv.".csv");
		//zipファイル内にテキストファイルを作成し、内容を追加
		//$zip->addFromString('foo.txt', '日本語でもおｋ？');
		
		$zip->close();
		if ( file_exists($csvf) ) {
			unlink($csvf) ;
		}
	}
	//エクスポート可能の場合
	//-----------------------------------

	if ($can_export) {
		$dao = new Class_M_INS_SHOP_RHIZOME;
		$filename = $aoki_batch_path_exp.$file_csv."_".$week_cd.".csv";
		if ($isbat) {
			
		}else {
			$tmpfilename = $file_csv."_".$week_cd."_".date("Ymd_His");
			header("Content-Type: application/octet-stream"); 
			header("Content-Disposition: attachment; filename=$tmpfilename.csv");	
		}
		//-------------------------チラシ経費データ出力---------------------------------------------------------------------
		if ($importsort == 4) {
			$data = $dao->searchfliercsv( $matrix_cd );
			//1 string code 2 integer 3 date 4 string ""必要 
				$col_heads = array(
					'flier_date'     => array( '配布年月',      2),
					'shop_cd'        => array( '店舗ｺｰﾄﾞ',          1),
					'media_name'     => array( '新聞社名',    1),
					'ins_shop_cd'    => array( '販売店コード',        1),
					'ins_shop_name'  => array( '販売店名',1),
					'verno'          => array( 'マトリクス№',    1),
					'title'          => array( 'チラシタイトル',    1),
					'size'           => array( 'チラシサイズ',        1),
					'pnums'          => array( '配布部数',          1),
					'now_cost'       => array( '経費',              1),
					'nowdate'        => array( 'ﾃﾞｰﾀ連携日',          1)
				);
				
				
				//列名
				foreach ($col_heads as $k=>$v) {
					$colums["name"][]   = $k;
					$colums["head"][]   = $v[0];
					$colums["type"][$k] = $v[1];
				}
				//データ整形開始
				foreach ($data as $k => $v) {
					$data[$k]["nowdate"] =  date("Ymd");
				}
				//データ整形完了
				$dao->output_csv($data, $colums);
				exit;
			}
			
			//-------------------------DM経費データ出力---------------------------------------------------------------------
			if ($importsort == 5) {
				$data = $dao->searchdmcsv( $matrix_cd );
				//データ整形開始
				foreach ($data as $k => $v) {
					$data[$k]["nowdate"] =  date("Ymd");
				}
				//データ整形完了
				//1 string code 2 integer 3 date 4 string ""必要 
				$col_heads = array(
					'dm_date'     => array( '投函日',      2),
					'shop_cd'     => array( '店舗ｺｰﾄﾞ',    1),
					'dm_no'       => array( '差替ＮＯ',      1),
					'title'       => array( 'DM名',        1),
					'begin_date'  => array( '有効期限（from）',  1),
					'end_date'    => array( '有効期限（to）',    1),
					'count'       => array( '投函数',       1),
					'money'       => array( '経費',         1),
					'nowdate'     => array( 'ﾃﾞｰﾀ連携日',   1)
				);
			
				//列名
				foreach ($col_heads as $k=>$v) {
					$colums["name"][]   = $k;
					$colums["head"][]   = $v[0];
					$colums["type"][$k] = $v[1];
				}
				if ($isbat) {
				
				}else {
					$dao->output_csv($data, $colums);
				}
				
				$dao->output_csv_file($data, $colums,$filename);
				
				$cnt                    = count($data);
				$errHtml                = "{$cnt}件データはエクスポートされました";
				$hvalues["end_time"]    = date("Y-m-d H:i:s",time());
				$hvalues["result_flg"]  = 0;
				$hvalues["result_msg"]  = $errHtml;
				$hdao->write_bhistory( $hvalues );
				exit;
		
			}
			//-------------------------DM経費データ出力---------------------------------------------------------------------
		}
	
		
if (!$isbat) {
?>
</body>
	</himl>
<?php
}


?>